package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.cache.service.IStrategyStatisVOService;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.repository.UserInfoRepository;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.util.AssertUtils;
import cn.wolfcode.luowowo.util.Consts;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Service
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private IUserInfoRedisService redisService;

    @Override
    public UserInfo findById(String id) {
        Optional<UserInfo> option = userInfoRepository.findById(id);
        if(option.get()!=null){
            return option.get();
        }
        return null;
    }

    //如果查到了返回true 判断手机号码是否唯一
    @Override
    public boolean checkPhone(String phone) {
        UserInfo u=userInfoRepository.findByPhone(phone);
        return u!=null;
    }

    @Override
    public void sendVerifyCode(String phone, String smsUrl, String appkey,String smsSign) {
        //生成验证码
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String verifyCode = uuid.substring(0, 4);
        StringBuilder sb = new StringBuilder(100);
        sb.append("你的验证码为: ").append(verifyCode).append(",在").append(Consts.VERIFY_CODE_VAI_TIME).append("分钟内操作有效");
        //将验证码发送到手机
        System.out.println(sb);
        //真实发送短信  原理：使用java方式发起http请求调用网关暴露接口
        //https://way.jd.com/chonry/smsapi?sign={1}&mobile={2}&content={3}&appkey={4}
        RestTemplate template = new RestTemplate();
        Map map= template.getForObject(smsUrl,Map.class,"【smsSign】",phone,sb.toString(),appkey);
        System.out.println(map);
        if(!map.get("code").equals("10000")){
            //短信发送失败
            throw new LogicException("短信发送失败");
        }
        //缓存验证码在redis中 因为后面注册要对验证码进行校验 设置验证码有效性为5分钟
        redisService.setVerifyCode(phone,verifyCode);
    }

    @Override
    public void regist(String phone,String nickname,String password,String rpassword,String verifyCode) {
        //判断参数是否为null
        AssertUtils.hasLength(phone,"手机号码不能为空");
        AssertUtils.hasLength(nickname,"昵称不能为空");
        AssertUtils.hasLength(password,"密码不能为空");
        AssertUtils.hasLength(rpassword,"确认密码不能为空");
        AssertUtils.hasLength(verifyCode,"验证码不能为空");
        //判断2次密码是否一致
        AssertUtils.isEquals(password,rpassword,"2次密码输入不一致");
        //判断手机号码格式是否正确  java正则
        //判断手机号码是否唯一
        if(this.checkPhone(phone)){
            throw new RuntimeException("手机号已经被注册 ");
        }
        //判断验证码是否一致
        //redis的code
        String code = redisService.getVerifyCode(phone);
        if(code==null || !code.equalsIgnoreCase(verifyCode)){
            throw new RuntimeException("验证码失效或错误");
        }
        //注册
        UserInfo userInfo = new UserInfo();
        userInfo.setPhone(phone);
        userInfo.setNickname(nickname);
        userInfo.setPassword(password);
        userInfo.setCity("");
        userInfo.setEmail("");
        userInfo.setGender(UserInfo.GENDER_SECRET);
        userInfo.setLevel(1);
        userInfo.setHeadImgUrl("/images/default.png");
        userInfo.setState(UserInfo.STATE_NORMAL);
        userInfo.setInfo("");
        userInfoRepository.save(userInfo);
    }


    @Override
    public UserInfo login(String username, String password) {
        UserInfo userInfo = userInfoRepository.findByPhone(username);
        if(userInfo==null || !password.equals(userInfo.getPassword())){
            throw new LogicException("账号或密码错误");
        }
        return userInfo;
    }

    @Override
    public List<UserInfo> list() {
        return userInfoRepository.findAll();
    }

    @Override
    public List<UserInfo> findByDestName(String destName) {
        return userInfoRepository.findByCity(destName);
    }

}
